package controller

/**
 * @title 用户控制层
 *
 * @author wz
 *
 * @date 2025/10/23 14:13
 *
 * @version 1.0
 */
import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"

	"test-gin/internal/model"
	"test-gin/internal/service"
)

// UserController 用户接口
type UserController struct {
	service *service.UserService
}

func NewUserController(db *gorm.DB) *UserController {
	return &UserController{
		service: service.NewUserService(db),
	}
}

// CreateUser 创建用户
func (c *UserController) CreateUser(ctx *gin.Context) {
	var user model.User
	if err := ctx.ShouldBindJSON(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "无效请求参数"})
		return
	}

	if err := c.service.CreateUser(&user); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "用户创建失败"})
		return
	}
	ctx.JSON(http.StatusCreated, user)
}

// GetUser 通过Id获取用户
func (c *UserController) GetUser(ctx *gin.Context) {
	id, _ := strconv.ParseUint(ctx.Param("id"), 10, 32)
	user, err := c.service.GetUserById(uint(id))
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			ctx.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
		} else {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
		}
		return
	}
	ctx.JSON(http.StatusOK, user)
}
